<template>
  <div class="ele-body">
    <el-card shadow="never">
      <el-form
        :model="where"
        label-width="77px"
        class="ele-form-search"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="IMEI:">
              <el-input
                clearable
                v-model="where.facilityImei"
                placeholder="请输入IMEI"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="设备型号:">
              <el-input
                clearable
                v-model="where.devModle"
                placeholder="请输入设备型号"/>
<!--              <el-select-->
<!--                clearable-->
<!--                v-model="where.model"-->
<!--                placeholder="请输入设备型号">-->
<!--                <el-option-->
<!--                  v-for="item in modelList"-->
<!--                  :key="item.value"-->
<!--                  :label="item.label"-->
<!--                  :value="item.value">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="软件版本:">
              <el-input
                clearable
                v-model="where.swVersion"
                placeholder="请输入软件版本"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <ele-pro-table
      ref="table"
      :where="where"
      :datasource="url"
      :columns="columns"
      :selection.sync="selection"
      @done="getCurrentTabelData"
      height="calc(100vh - 315px)">
      <!-- 表头工具栏 -->
      <template slot="toolbar">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="openEdit(null)"
          v-if="permission.includes('sys:level:add')">批量导入
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-delete"
          class="ele-btn-icon"
          @click="unbindAll"
        >批量解绑
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-refresh"
          class="ele-btn-icon"
          @click="rebootBatch"
          v-if="permission.includes('sys:level:dall')">批量重启
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-refresh"
          class="ele-btn-icon"
          @click="returnAllPlay"
          >批量恢复出厂设置
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-refresh"
          class="ele-btn-icon"
          @click="allChangeDHCP"
        >批量修改DHCP
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-refresh"
          class="ele-btn-icon"
          @click="allChangeCMD"
        >批量修改 - AT命令
        </el-button>
<!--        <el-button-->
<!--          @click="showImport=true"-->
<!--          icon="el-icon-upload2"-->
<!--          class="ele-btn-icon"-->
<!--          size="small"-->
<!--          v-if="permission.includes('sys:level:import')">导入-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          size="small"-->
<!--          type="success"-->
<!--          icon="el-icon-download"-->
<!--          class="ele-btn-icon"-->
<!--          @click="exportExcel"-->
<!--          v-if="permission.includes('sys:level:export')">导出-->
<!--        </el-button>-->
      </template>
      <!-- 操作列 -->
      <template slot="action" slot-scope="{row}">
<!--        <el-popconfirm-->
<!--          class="ele-action"-->
<!--          title="确定要重启此设备么？"-->
<!--          @confirm="action(row,'reboot')">-->
<!--          <el-link-->
<!--            type="primary"-->
<!--            slot="reference"-->
<!--            :underline="false"-->
<!--            icon="el-icon-delete"-->
<!--            v-if="permission.includes('sys:level:delete')">重启-->
<!--          </el-link>-->
<!--        </el-popconfirm>-->
<!--        <el-popconfirm-->
<!--          class="ele-action"-->
<!--          title="确定要恢复出厂设置？"-->
<!--          @confirm="action(row,'reset')">-->
<!--          <el-link-->
<!--            type="danger"-->
<!--            slot="reference"-->
<!--            :underline="false"-->
<!--            icon="el-icon-delete"-->
<!--            v-if="permission.includes('sys:level:delete')">恢复出厂设置-->
<!--          </el-link>-->

<!--        </el-popconfirm>-->
        <el-link
          type="primary"
          slot="reference"
          :underline="false"
          icon="el-icon-view"
          style="height: 60px;"
          @click="showDetail(row)"
        >查看详情
        </el-link>
      </template>
      <!-- 状态列 -->
<!--      <template slot="status" slot-scope="{row}">-->
<!--        <el-switch-->
<!--          v-model="row.status"-->
<!--          @change="editStatus(row)"-->
<!--          :active-value="1"-->
<!--          :inactive-value="2"/>-->
<!--      </template>-->
    </ele-pro-table>

    <el-dialog
      :title="wifiOptionName"
      :visible="visible"
      width="460px"
      :destroy-on-close="true"
      :lock-scroll="false">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px">
        <el-form-item
          v-if="wifiOption===1"
          label="wifi名称:"
          prop="ssidName">
          <el-input
            :maxlength="200"
            v-model="form.ssidName"
            placeholder="请输入wifi名称"
            clearable/>
        </el-form-item>
        <el-form-item
          v-if="wifiOption===2"
          label="wifi密码:"
          prop="ssidPwd">
          <el-input
            :maxlength="200"
            v-model="form.ssidPwd"
            placeholder="请输入wifi标识"
            clearable/>
        </el-form-item>
        <el-form-item
          v-if="wifiOption===3"
          label="自定义指令:"
          prop="cmd">
          <el-input
            :maxlength="200"
            v-model="form.cmd"
            placeholder="请输入自定义指令"
            clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="updateVisible(false)">取消</el-button>
        <el-button
          type="primary"
          @click="save"
          :loading="loading">保存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="设备用户详情"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      custom-class="dialogClass"
      >
      <el-form label-position="left" ref="form">
        <el-row>
          <!-- 第一栏 用户-->
          <el-col :span="9">
            <el-row>
              <el-col :span="5">
                <div style="vertical-align: middle;text-align: left">
                  <img :src="crueentDeatail.avatar||wxImg" alt="" width="75" height="75">
                </div>
              </el-col>
              <el-col :span="18">
                <el-form label-width="68px">
                  <el-form-item label="微信名：">
                    {{ crueentDeatail.nickname?crueentDeatail.nickname:isNoData}}
                  </el-form-item>
                  <el-form-item label="微信ID：">
                    {{ crueentDeatail.openId?crueentDeatail.openId:isNoData }}
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-form  label-width="82px">
              <el-row>
              <el-col :span="24">
                <el-form-item label="注册时间：">
                  {{crueentDeatail.createTime?crueentDeatail.createTime:isNoData}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="城市：">
                  {{crueentDeatail.cityName?crueentDeatail.cityName:isNoData}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="用户地址：">
                  {{crueentDeatail.address?crueentDeatail.address:isNoData}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="操作： ">
                  <el-button type="warning" v-if="crueentDeatail.openId" @click="unbind(crueentDeatail)">解除绑定</el-button>
                  <el-button type="warning" v-else >解除绑定</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            </el-form>
          </el-col>
          <!-- 竖线 -->
          <el-col :span="1">
            <div class="tabline"></div>
          </el-col>
          <!-- 第二栏 设备-->
          <el-col :span="14" >
            <el-col>
              <el-form label-width="82px">
              <el-row>
              <el-col :span="3">
                <div style="vertical-align: middle;text-align: left">
                  <img :src="shebei" alt="" width="75" height="75">
                </div>
              </el-col>
              <el-col :span="20">
                <el-col >
                  <el-form-item label="IMEI：">
                  {{crueentDeatail.imei?crueentDeatail.imei:isNoData}}
                </el-form-item>
              </el-col >
              <el-col >
                  <el-form-item label="设备型号：">
                  {{crueentDeatail.devModel?crueentDeatail.devModel:isNoData}}
                </el-form-item>
              </el-col >
              </el-col>
            </el-row>
            </el-form>
            </el-col>
            <el-col>
              <el-form label-width="138px">
              <el-row>
              <el-col>
                <el-form-item label="在线时长：">
                  {{changeTime}}
                </el-form-item>
                <el-form-item label="最后一次上线时间：">
                  {{crueentDeatail.updateTime?crueentDeatail.updateTime:isNoData}}
                </el-form-item>
              </el-col>
            </el-row>
            </el-form>
            </el-col>
            <el-col>
              <el-tabs type="border-card" v-model="activeName">
                            <el-tab-pane  class="dd-tabs_content" label="WIFI设置">
                              <el-form :model="crueentDeatail" :rules="rules" :hide-required-asterisk="isHideLine" :inline-message="isHideLine" label-width="75px">
                                <el-col :span="24">
                                  <el-form-item label="WIFI名称: " prop="ssidName">
                                    <el-input v-model="crueentDeatail.ssidName" placeholder="请输入WIFI名称" clearable class="device-details-input" ></el-input>
                                  </el-form-item>
                                  <el-form-item label="WIFI密码: " prop="ssidPassword">
                                    <el-input v-model="crueentDeatail.ssidPassword" show-password  placeholder="请输入WIFI密码" clearable class="device-details-input" ></el-input>
                                  </el-form-item>
                                </el-col>
                              <el-col>
                                <el-button class="wifisubmit" type="primary" @click="saveWifi(crueentDeatail)">保 存</el-button>
                              </el-col>
                              </el-form>
                            </el-tab-pane>
                            <el-tab-pane class="dd-tabs_content" label="LAN设置">
                              <el-form :hide-required-asterisk="isHideLine" :inline-message="isHideLine" ref="HDForm" label-width="128px" :model="DHCPform" :rules="HDrules">
                                    <el-col >
                                      <el-form-item label="IP地址: " prop="ipAddr">
                                        <el-input v-model="DHCPform.ipAddr" :rules="HDrules.ipAddr" placeholder="输入IP地址" clearable class="device-details-input"></el-input>
                                      </el-form-item>
                                    </el-col >
                                    <el-col >
                                      <el-form-item label="子网掩码: " prop="subnetMask">
                                        <el-input v-model="DHCPform.subnetMask" :rules="HDrules.subnetMask" placeholder="请输入子网掩码" clearable class="device-details-input"></el-input>
                                      </el-form-item>
                                    </el-col>
                                    <el-col >
                                      <el-form-item label="IP地址池开始地址:" prop="startIpAddr">
                                        <el-input v-model="DHCPform.startIpAddr" :rules="HDrules.startIpAddr" placeholder="请输入IP地址池开始地址" clearable class="device-details-input"></el-input>
                                      </el-form-item>
                                    </el-col >
                                    <el-col >
                                      <el-form-item label="IP地址池结束地址:" prop="endIpAddr">
                                        <el-input v-model="DHCPform.endIpAddr" :rules="HDrules.endIpAddr" placeholder="请输入IP地址池结束地址" clearable class="device-details-input"></el-input>
                                      </el-form-item>
                                    </el-col>
                                </el-form>
                              <el-button class="wifisubmit" type="primary" @click="submitDHCP">保 存</el-button>
                              </el-tab-pane>
                            <el-tab-pane class="dd-tabs_content" label="其他操作">
                                  <el-button class="dd-tab-btn" type="primary" @click="restart">重&emsp;启</el-button>
                                  <el-button class="dd-tab-btn" type="primary" @click="returnPlay">恢复出厂设置</el-button>
                            </el-tab-pane>
                            <el-tab-pane class="dd-tabs_content" label="设备详情">
                              <el-form label-width="88px">
                                <el-col>
                                <el-form-item label="IMEI: ">
                                  {{crueentDeatail.imei?crueentDeatail.imei:isNoData}}
                                </el-form-item>
                              </el-col >
                              <el-col>
                                <el-form-item label="软件版本: ">
                                  {{crueentDeatail.swVersion?crueentDeatail.swVersion:isNoData}}
                                </el-form-item>
                              </el-col >
                              <el-col >
                                <el-form-item label="IMSI: ">
                                  {{crueentDeatail.imsi?crueentDeatail.imsi:isNoData}}
                                </el-form-item>
                              </el-col >
                            <el-col >
                              <el-form-item label="ICCID: ">
                                {{crueentDeatail.iccid?crueentDeatail.iccid:isNoData}}
                              </el-form-item>
                            </el-col>
                              <el-col >
                                <el-form-item label="设备型号: ">
                                  {{crueentDeatail.devModel?crueentDeatail.devModel:isNoData}}
                                </el-form-item>
                              </el-col >
                              <el-col >
                                <el-form-item label="MAC地址: ">
                                  {{crueentDeatail.macAddr?crueentDeatail.macAddr:isNoData}}
                                </el-form-item>
                              </el-col>
                              <el-col >
                                <el-form-item label="信号强度: ">
                                  {{crueentDeatail.networkStrength?crueentDeatail.networkStrength:isNoData}}
                                </el-form-item>
                              </el-col >
                              <el-col >
                                <el-form-item label="在线总时长: ">
                                  {{changeTime}}
                                </el-form-item>
                              </el-col>
                            </el-form>
                            </el-tab-pane>
<!--                <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane>-->
              </el-tabs>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="上传模版"
      :visible="updataShow"
      width="460px"
      :destroy-on-close="true"
      :lock-scroll="false"
      :before-close="closeUpdata">
      <div style="text-align: center;">
        <el-upload
          drag
          action=""
          class="ele-block"
          v-loading="upDataLoading"
          accept=".xls,.xlsx"
          :show-file-list="true"
          :before-upload="beforeUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
          <div class="el-upload__tip ele-text-center" slot="tip">
            <span>只能上传xls、xlsx文件，</span>
            <el-link
              download
              type="primary"
              :underline="false"
              style="vertical-align: baseline;"
              @click="downloadExcel">下载模板
            </el-link>
          </div>
        </el-upload>
      </div>
    </el-dialog>

    <el-dialog
      title="批量修改DHCP"
      :visible="DHCPShow"
      width="460px"
      :destroy-on-close="true"
      :lock-scroll="false"
      :before-close="closeDHCPShow">
      <div style="text-align: center;">
        <el-form :hide-required-asterisk="isHideLine" :inline-message="isHideLine" ref="allDHCPForm" label-width="128px" :model="allDHCPform" :rules="HDrules">
          <el-col >
            <el-form-item label="IP地址: " prop="ipAddr">
              <el-input v-model="allDHCPform.ipAddr" :rules="HDrules.ipAddr" placeholder="输入IP地址" clearable class="device-details-input"></el-input>
            </el-form-item>
          </el-col >
          <el-col >
            <el-form-item label="子网掩码: " prop="subnetMask">
              <el-input v-model="allDHCPform.subnetMask" :rules="HDrules.subnetMask" placeholder="请输入子网掩码" clearable class="device-details-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col >
            <el-form-item label="IP地址池开始地址:" prop="startIpAddr">
              <el-input v-model="allDHCPform.startIpAddr" :rules="HDrules.startIpAddr" placeholder="请输入IP地址池开始地址" clearable class="device-details-input"></el-input>
            </el-form-item>
          </el-col >
          <el-col >
            <el-form-item label="IP地址池结束地址:" prop="endIpAddr">
              <el-input v-model="allDHCPform.endIpAddr" :rules="HDrules.endIpAddr" placeholder="请输入IP地址池结束地址" clearable class="device-details-input"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <span slot="footer" class="dialog-footer">
           <el-button type="success" @click="allDHCPUpdate">提交</el-button>
        <el-button type="primary" @click="DHCPShow = false">关 闭</el-button>
      </span>
      </div>
    </el-dialog>
    <el-dialog
      title="批量修改自定义指令"
      :visible="CMDShow"
      width="460px"
      :destroy-on-close="true"
      :lock-scroll="false"
      :before-close="closeCMDShow">
      <div style="text-align: center;">
        <el-form :hide-required-asterisk="isHideLine" :inline-message="isHideLine" ref="allCMDForm" label-width="128px" :model="allCMDform" :rules="CMDrules">
          <el-col >
            <el-form-item label="自定义命令: " prop="cmd">
              <el-input v-model="allCMDform.cmd" placeholder="输入自定义指令" clearable class="device-details-input"></el-input>
            </el-form-item>
          </el-col >
        </el-form>
        <span slot="footer" class="dialog-footer">
           <el-button type="success" @click="allCMDpdate">提交</el-button>
        <el-button type="primary" @click="CMDShow = false">关 闭</el-button>
      </span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { mapGetters } from "vuex";
  import wxImg from '../../../assets/logo.png'
  import shebei from '../../../assets/shebei.png'
  import axios from "axios";
  export default {
    data(){
      // 校验WIFI名
      let wifiNameInput = (rule, value, callback) => {
	      if (!this.checkSpecialKey(value)) {
          this.invalidWifi = true
	        callback(new Error("请输入有效的WIFI名称"));
	      } else {
          this.invalidWifi = false
	        callback();
	      }
	    };
      let wifipwInput = (rule, value, callback) => {
	      if (!this.checkSpecialKey1(value)) {
          this.invalidWifi = true
	        callback(new Error("请输入有效的WIFI密码"));
	      } else {
          this.invalidWifi = false
	        callback();
	      }
	    };
      // 校验ip地址
      let validateName = (rule, value, callback) => {
        if(value && "..." === value){
          callback(new Error('请输入IP地址'))
        }if (value && !(/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/).test(value)) {
          callback(new Error('IP地址不规范'))
        } else {
          callback()
        }
      }
      // 校验子网掩码
      let trueSubnetMask = (rule, value, callback) => {
        console.log(value)
        var rep = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
          if(value && "..." === value){
            callback(new Error('请输入子网掩码'))
          }
          if(!rep.test(value)){
            callback(new Error("子网掩码不规范"));
          }
          else{
            callback()
          }
      }
      return {
        activeName:'',
        isHideLine:true,
        updataShow:false,
        DHCPShow:false,
        invalidWifi:false,
        changeTime:'---',
        isNoData:'---',
        shebei,
        modelList:[

        ],
        where: {

        },
        url: '/mf-facility/getWebFacility',
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: "left",
            selectable:this.selectable
          },
          {
            columnKey: 'index',
            type: 'index',
            width: 45,
            align: 'center',
            fixed: "left",
            label: '序号',
          },
          {
            prop: 'facilityImei',
            label: 'IMEI',
            align: 'center',
            showOverflowTooltip: true,
            width: 200,
            // formatter: (row, column, cellValue) => {
            //   console.log(row)
            //   if(row.facilityStatus == 1){
            //     return '在线'
            //   }else if(row.facilityStatus == 2){
            //     return '离线'
            //   }
            // }
          },
          {
            prop: 'devModel',
            label: '设备型号',
            align: 'center',
            showOverflowTooltip: true,
            // formatter: (row, column, cellValue) => {
            //   console.log(row)
            //   if(row.facilityStatus == 1){
            //     return '在线'
            //   }else if(row.facilityStatus == 2){
            //     return '离线'
            //   }
            // }
          },
          {
            prop: 'swVersion',
            label: '软件版本',
            width: 200,
            align: 'center',
            showOverflowTooltip: true,
          },
          {
            prop: 'facilityStatus',
            label: '设备状态',
            showOverflowTooltip: true,
            minWidth: 200,
            align: 'center',
            formatter: (row, column, cellValue) => {
              console.log(row)
              if(row.facilityStatus == 1){
                return '在线'
              }else if(row.facilityStatus == 2){
                return '离线'
              }
            }
          },
          {
            prop: 'exUserStatus',
            label: '是否有效用户',
            sortable: 'custom',
            align: 'center',
            width: 150,
            resizable: false,
            formatter: (row, column, cellValue) => {
              console.log(row)
              if(row.exUserStatus == 1){
                return '有效'
              }else if(row.exUserStatus == 2){
                return '无效'
              }
            }
          },
          {
            prop: 'agent',
            label: '所属代理商',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'updateTime',
            label: '最后一次上线时间',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 160,
            align: 'center',
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: "right"
          }
        ],
        selection: [],
        // 当前编辑数据
        current: {},
        // 是否显示编辑弹窗
        showEdit: false,
        // 是否显示导入弹窗
        showImport: false,
        wifiOption:null,
        visible:false,
        form:{
          ssidPassword:'',
          ssidName:'',
          cmd:'',
          userId:'',
          id:'',
          facilityImei:''
        },
        rules:{
          ssidName:[
            {required: true, message: 'WIFI名称不能为空', trigger: 'change'},
            {max:32,message:"WIFI名称长度不能超过32位",trigger: 'change'},
            {validator: wifiNameInput ,trigger: 'change'},
          ],
          ssidPassword:[
            {required: true, message: 'WIFI密码不能为空', trigger: 'change' },
            {max:63,message:"WIFI密码长度不能超过63位",trigger: 'change'},
            {min:8,message:"WIFI密码长度不能少于8位",trigger: 'change'},
            {validator: wifipwInput ,trigger: 'change'},

          ]
        },
        CMDrules:{
          cmd:[
            {required: true, message: '自定义命令不得为空', trigger: 'change'},
          ]
        },
        HDrules:{
          ipAddr:[
            {required: true, message: 'IP地址不能为空', trigger: 'change'},
            {message: '请输入正确IP地址', trigger: 'change',validator: validateName},
          ],
          subnetMask:[
            {required: true, message: '子网掩码不能为空', trigger: 'change'},
            {validator: trueSubnetMask ,trigger: 'change'},
          ],
          startIpAddr:[
            { required: true, message: '请输入IP地址池开始地址', trigger: 'change' },
            {  message: '请输入正确IP地址池开始地址', trigger: 'change',validator: validateName  },
          ],
          endIpAddr:[
            { required: true, message: '请输入IP地址池结束地址', trigger: 'change' },
            {  message: '请输入正确IP地址池结束地址', trigger: 'change',validator: validateName  },
          ],
        },
        loading:false,
        dialogVisible:false,//弹窗
        crueentDeatail:{},
        userId:'',
        facilityId:'',
        HDdialogVisible:false,
        DHCPform:{},
        allDHCPform:{
          ipAddr:'',
          subnetMask:'',
          startIpAddr:'',
          endIpAddr:''
        },
        upDataLoading:false,
        wxImg,
        currentTabelData:[], // 当前页面数据
        tabelref:'', // tablerefs
        selectionAll:[], // 所有的选中
        allCMDform:{
          cmd:''
        },
        CMDShow:false,
      }
    },
    watch:{
      selection(newValue){
        let hashObj = {}
        this.currentTabelData.forEach(iitem=>{
          hashObj[iitem.id] = true
        })
        let list = []
        this.selectionAll.forEach(item=>{
           if(!hashObj[item.id]){
             list.push(item)
           }
        })
        this.selectionAll = list
        this.selectionAll.push(...newValue)
      },
      selectionAll(newValue){
        console.log('selectionAll', newValue)
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      wifiOptionName(){
        if(this.wifiOption === 1){
          return '修改wifi名称'
        }else if(this.wifiOption === 2){
          return '修改wifi密码'
        }else if(this.wifiOption === 3){
          return '自定义指令'
        }
      }
    },
    created() {
      console.log(this.crueentDeatail.sumDuration)
    },
    methods: {
      allChangeCMD(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        this.CMDShow = true;
        this.allCMDform = {
          cmd:''
        }
      },
      allChangeDHCP(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        this.DHCPShow = true;
        this.allDHCPform = {
          ipAddr:'',
          subnetMask:'',
          startIpAddr:'',
          endIpAddr:''
        }
      },
      // selection是否能选中
      selectable(row){
        if(row.facilityStatus === 1){
          return true
        }else {
          return true
        }
      },
      // 当前页的搜索结果
      getCurrentTabelData(data, page, total, $table){
        console.log('当前的data', data)
        this.currentTabelData = data.data.records
        this.tabelref = $table
        console.log($table)
        this.toggleSelection()
      },
      // 默认选中
      toggleSelection(){
        this.selectionAll.forEach(item=>{
          this.currentTabelData.forEach(iitem=>{
            if(item.id === iitem.id){
              this.$nextTick(()=>{
                this.tabelref.toggleRowSelection(iitem, true)
              })
            }
          })
        })
      },
      // 批量重启
      rebootBatch(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        this.$confirm('确定要重启选择的设备?', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({lock: true});
          let params = this.selectionAll.map(item=>{
            return {
              userId:item.userId,
              facilityId: item.id,
              "operationType": "reboot"
            }
          })
          this.$http.post('/common/web/operationWebListFacility',params).then(res => {
            loading.close();
            if (res.data.code === 0) {
              this.$message({type: 'success', message: res.data.msg});
              this.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        }).catch(() => {
        });
      },
      //input操作未反应，强制刷新
      inputChange(){
        this.$forceUpdate();
      },
      //弹窗 state:success / info / warning / error
      openAlert(msg,title,state){
        this.$alert(msg, title,{
          confirmButtonText: '确定',
          type: state
        });
      },
      // wifi名称校验不能有特殊字符，收尾不能是空格
      checkSpecialKey(str) {
      let pattern1 = /^\s+/g;
	    let pattern2 = /\s+$/g;
      if (pattern1.test(str)||pattern2.test(str)){
         return false;
      }
      let specialKey ="`·！￥$……&*（）【】[]\\、:：;；'‘\"“,，。<>《》、？";
        // "[`~!#$^&*()=|{}':;'\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
      for (let i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) != -1) {
          return false;
        }
      }
      return true;
    },
    checkSpecialKey1(str) {
      let specialKey =" `·！￥$……&*（）【】[]\\、:：;；'‘\"“,，。<>《》、？";
        // "[`~!#$^&*()=|{}':;'\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
      for (let i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) != -1) {
          return false;
        }
      }
      return true;
    },
      /* 刷新表格 */
      reload() {
        this.$refs.table.reload({where: this.where});
      },
      /* 重置搜索 */
      reset() {
        this.where = {};
        this.reload();
      },
      /* 显示编辑 */
      openEdit(row) {
        this.updataShow = true
        // console.log(this.permission.includes('sys:level:add'))
        // this.current = row;
        // this.showEdit = true;
      },
      /* 删除 */
      remove(row) {
        const loading = this.$loading({lock: true});
        this.$http.delete('/level/delete/' + [row.id]).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      },
      //操作
      action(row,option){
        const loading = this.$loading({lock: true});
        this.$http.post('/common/web/operationFacility',{
          facilityId:row.facilityId,
          operationType:option
        }).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      },
      updateVisible(){
        this.visible = false;
        this.form = {
          ssidPassword:'',
          ssidName:'',
          cmd:'',
          userId:'',
          id:'',
          facilityImei:''
        }
      },
      optionWifi(type,row){
        this.visible = true;
        this.wifiOption = type;
        this.current = row;
        for(let key in this.form){
         if(row[key]){
           this.form[key] = row[key]
         }
        }
        },
      saveWifi(row){
        if(row.ssidName == ""|| row.ssidPassword == "" || this.invalidWifi){
          return false
        }
        let operationType = this.wifiOption===3?'cmd':'wifi';
        this.$http.post('/common/web/operationWebFacility',{
          facilityId:row.facilityId,
          operationType:operationType,
          data: {
            key:operationType,
            ssidName:row.ssidName,
            ssidPassword:row.ssidPassword
          }
        }).then(res => {
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.openAlert(res.data.msg,"失败","error")
            // this.$message.error(res.data.msg);
          }
        }).catch(e => {
          this.$message.error(e.message);
        });
      },
      save(){
        this.$refs['form'].validate((valid) => {
          if(valid){
            let operationType = this.wifiOption===3?'cmd':'wifi'
            this.loading = true;
            this.$http.post('/common/web/operationWebFacility',{
              facilityId:this.current.facilityId,
              operationType:operationType,
              data:{...this.form, key:operationType,}
            }).then(res => {
              console.log(res)
              this.loading = false
              if (res.data.code === 0) {
                this.visible = false;
                this.$message.success(res.data.msg);
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(e => {
              this.loading = false
              this.$message.error(e.message);
            });
          }
        })
      },
      showDetail(row){
        // debugger
        console.log(row)
        this.crueentDeatail = {}
        this.changeTime = '---'
        this.DHCPform = {}
        this.facilityId = row.id;
        this.userId = row.userId
        this.$http.post('/common/web/getFacilityInfo',{facilityId:row.id}).then(res => {
          if (res.data.code === 0) {
            let data = res.data.data||{}
            console.log('data1',data)
            this.crueentDeatail = {...this.crueentDeatail,...data}
            this.setSumTime(this.crueentDeatail.sumDuration)
          }
        })
        this.$http.post('/common/web/getDhcpInfo',{facilityId:row.id}).then(res => {
          if (res.data.code === 0) {
            let data = res.data.data||{}
            this.DHCPform = data;
            this.$set(this.DHCPform,'startIpAddr',data.ipPoolBegin)
            this.$set(this.DHCPform,'endIpAddr',data.ipPoolEnd)
            // this.DHCPform.startIpAddr = data.ipPoolBegin
            // this.DHCPform.endIpAddr = data.ipPoolEnd
            console.log('data2',data)
            this.crueentDeatail = {...this.crueentDeatail,...data}
          }
        })

        this.$http.post('/common/web/getUser',{userId:row.userId}).then(res => {
          if (res.data.code === 0) {
            let data = res.data.data||{}
            this.crueentDeatail = {...this.crueentDeatail,...data}
          }
        })

        //这里放入微信相关信息
        // this.crueentDeatail.wxName = '勤奋波'
        // this.crueentDeatail.wxTime = '2021-03-06 ~ 2022-02-28(365天)'
        // this.crueentDeatail.wxId = '21321dfnfnasi123klnfkdsanfl'
        // this.crueentDeatail.wxCityName = '南京'
        // this.crueentDeatail.wxAddress = '南京雨花台区'
        // this.crueentDeatail.useTime = '2020-03-06 ~ 2022-03-05' //设备使用时间
        // this.crueentDeatail.timeLength = '10小时35分28秒';//在线总时长

        this.dialogVisible = true;
        console.log(row)
      },
      //时间转化 分钟 → xx小时xx分钟
      setSumTime(min){
        console.log(min)
        let h = Math.floor(min / 60);
        min -= h * 60;
        this.changeTime = h? (h + "小时" + min + "分钟") : (min + "分钟")
      },
      DHhandleClose(){
        this.HDdialogVisible = false
      },
      closeUpdata(){
        this.updataShow = false
      },
      closeDHCPShow(){
        this.DHCPShow = false
      },
      closeCMDShow(){
        this.CMDShow = false
      },
      allCMDpdate(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        let params = this.selectionAll.map(item=>{
          return {
            userId:item.userId,
            facilityId: item.id,
            operationType:'cmd',
            data:{...this.allCMDform, key:'cmd'}
          }
        })
        this.$refs['allCMDForm'].validate((check)=>{
          if(check){
            this.$http.post('/common/web/operationWebListFacility', params).then(res => {
              if (res.data.code === 0) {
                this.$message({
                  type: 'success',
                  message: '请在修改记录里面查看结果'
                });
                this.DHCPShow = false
                this.reload()
              }else {
                this.$message({
                  type: 'error',
                  message:res.data.msg
                });
              }
            })
          }
        })
      },
      allDHCPUpdate(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        if(this.allDHCPform.ipAddr==""|| this.allDHCPform.startIpAddr==""||this.allDHCPform.endIpAddr==""){
          this.$message.error('请填写表单')
          return false
        }
        //比较ip地址前三段
        var arg = this.allDHCPform.ipAddr
        var argBegin = this.allDHCPform.startIpAddr
        var argEnd = this.allDHCPform.endIpAddr
        var regEx = /\./g
        var ipList = arg.toString().replace(regEx, ',').split(',')
        var ipBeginList = argBegin.toString().replace(regEx, ',').split(',')
        var ipEndList = argEnd.toString().replace(regEx, ',').split(',')
        for (var i=0;i<3;i++){
          if(ipBeginList[i] != ipEndList[i] ||  ipEndList[i] != ipList[i] || ipBeginList[i] != ipList[i]){
            this.openAlert("IP地址超出局域网子网范围。","提示","error")
            return false
          }
        }
        if(parseInt(ipBeginList[3]) <= parseInt(ipList[3]) && parseInt(ipList[3]) <= parseInt(ipEndList[3])){
          this.openAlert("IP 地址池不能包含局域网 IP 地址（DHCP 起始地址应该比局域网 IP 地址大）。","提示","error")
          return false
        }
        if(parseInt(ipBeginList[3]) > parseInt(ipEndList[3])){
          this.openAlert("无效的IP地址,起始地址不能大于结束地址。","提示","error")
          return false
        }
        let params = this.selectionAll.map(item=>{
          return {
            userId:item.userId,
            facilityId: item.id,
            operationType:'dhcp',
            data:{...this.allDHCPform, key:'dhcp'}
          }
        })
        this.$refs['allDHCPForm'].validate((check)=>{
          if(check){
            this.$http.post('/common/web/operationWebListFacility', params).then(res => {
              if (res.data.code === 0) {
                this.$message({
                  type: 'success',
                  message: '请在修改记录里面查看结果'
                });
                this.DHCPShow = false
                this.reload()
              }else {
                this.$message({
                  type: 'error',
                  message:res.data.msg
                });
              }
            })
          }
        })
      },
      restart(){
        this.$confirm('此操作要重启设备，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post('/common/web/operationFacility',{userId:this.userId,facilityId:this.facilityId,operationType:'reboot'}).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                message: '重启成功'
              });
              this.reload()
            }else {
              this.$message({
                type: 'error',
                message:res.data.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重启'
          });
        });
      },
      returnAllPlay(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        this.$confirm('此操作要恢复出厂设置此设备，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = this.selectionAll.map(item=>{
            return {
              userId:item.userId,
              facilityId: item.id,
              "operationType": "reset"
            }
          })
          this.$http.post('/common/web/operationWebListFacility', params).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                message: '恢复出厂设置成功'
              });
              this.reload()
            }else {
              this.$message({
                type: 'error',
                message:res.data.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消恢复出厂设置'
          });
        });
      },
      returnPlay(){
        this.$confirm('此操作要恢复出厂设置此设备，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post('/common/web/operationFacility',{userId:this.userId,facilityId:this.facilityId,operationType:'reset'}).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                message: '恢复出厂设置成功'
              });
              this.reload()
            }else {
              this.$message({
                type: 'error',
                message:res.data.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消恢复出厂设置'
          });
        });
      },
      handleDHCP(){
        this.HDdialogVisible = true;
      },
      // 校验ip地址池
      submitDHCP(){
        // ip为空
        if(this.DHCPform.ipAddr==""|| this.DHCPform.startIpAddr==""||this.DHCPform.endIpAddr==""){
          return false
        }
        // ip是否有变化
        let ipNoChange = this.crueentDeatail.ipAddr == this.DHCPform.ipAddr && this.crueentDeatail.startIpAddr == this.DHCPform.startIpAddr && this.crueentDeatail.endIpAddr == this.DHCPform.endIpAddr && this.crueentDeatail.subnetMask == this.DHCPform.subnetMask
        if(ipNoChange){
          this.openAlert("您的设置未发生变化。","提示","error")
          return false
        }
        //比较ip地址前三段
        var arg = this.DHCPform.ipAddr
        var argBegin = this.DHCPform.startIpAddr
        var argEnd = this.DHCPform.endIpAddr
        var regEx = /\./g
        var ipList = arg.toString().replace(regEx, ',').split(',')
        var ipBeginList = argBegin.toString().replace(regEx, ',').split(',')
        var ipEndList = argEnd.toString().replace(regEx, ',').split(',')
        for (var i=0;i<3;i++){
          if(ipBeginList[i] != ipEndList[i] ||  ipEndList[i] != ipList[i] || ipBeginList[i] != ipList[i]){
            this.openAlert("IP地址超出局域网子网范围。","提示","error")
            return false
          }
        }
        if(parseInt(ipBeginList[3]) <= parseInt(ipList[3]) && parseInt(ipList[3]) <= parseInt(ipEndList[3])){
          this.openAlert("IP 地址池不能包含局域网 IP 地址（DHCP 起始地址应该比局域网 IP 地址大）。","提示","error")
          return false
        }
        if(parseInt(ipBeginList[3]) > parseInt(ipEndList[3])){
          this.openAlert("无效的IP地址,起始地址不能大于结束地址。","提示","error")
          return false
        }
        this.$refs['HDForm'].validate((valid) => {
            if (valid) {
              let obj = {
                userId:this.userId,
                facilityId:this.facilityId,
                operationType:'dhcp',
                data:{...this.DHCPform, key:'dhcp'}
              }
              this.$http.post('/common/web/operationFacility',obj).then(res => {
                this.HDdialogVisible = false;
                if (res.data.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '修改LAN设置成功'
                  });
                }
                else{
                  this.openAlert(res.data.msg,"失败","error")
                }
              }).catch(err=>{
                this.HDdialogVisible = false;
              })
            } else {
              console.log('error submit!!');
              return false;
            }


        });

      },
      handleClose(){
        this.dialogVisible = false
      },
      unbindAll(){
        if (!this.selectionAll.length) {
          this.$message.error('请至少选择一个设备')
          return;
        }
        this.$confirm('是否要解除绑定?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = this.selectionAll.map(item=>{
            return {
              id: item.id,
            }
          })
          this.$http.post('/common/web/unbindFacilityList',params).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                message: '解除绑定成功'
              });
              this.reload()
            }else {
              this.$message({
                type: 'error',
                message:res.data.msg
              });
            }

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解除绑定'
          });
        });
      },
      unbind(row){
        this.$confirm('是否要解除绑定?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post('/common/web/unbindFacility',{id:this.facilityId}).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                message: '解除绑定成功'
              });
              this.reload()
            }else {
            this.$message({
              type: 'error',
              message:res.data.msg
            });
          }

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解除绑定'
          });
        });
      },
      /* 上传 */
      beforeUpload(file) {
        this.loading = true;
        let formData = new FormData();
        formData.append('file', file);
        this.$http.post('/common/web/impMfFacility', formData).then(res => {
          this.loading = false;
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg});
            // this.updateVisible(false);
            // this.$emit('done');
            this.updataShow = false
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          this.loading = false;
          this.$message.error(e.message);
        });
        return false;
      },
      /**
       * 下载模板
       */
      downloadExcel() {
        if(location.host.includes('127.0.0.1')||location.host.includes('47.96.14.96')||location.host.includes('test.business.signalinks')){
          window.open( process.env.VUE_APP_API_BASE_DODN+'dist/导入模版.xlsx')
        }else {
          window.open( process.env.VUE_APP_API_BASE_DODN+'dist/导入模版.xlsx')
        }
        //window.location.href = axios.defaults.baseURL + "/common/download?fileName="+ encodeURI("level.xlsx") +"&isDelete=" + false;
      }
    }
  }
</script>
<style scoped>
  .height30{
    height: 30px;
    vertical-align: middle;
    line-height: 30px;
  }
  .submitImg{
    vertical-align: middle;
    margin-left: 2px;
  }
  .ele-block{
    text-align: center;
  }
  .device-details-input{
    width: 85%;
  }
.wifisubmit{
  position: absolute;
  right: 0px;
  bottom: 0px;
}
.tabline{
  width: 1px;
  height: 580px;
  background: black;
}
.el-tabs--border-card{
border: none;
box-shadow: none;
}
.dd-tabs_content{
  margin-top: 20px;
  height: 330px;
}
.userDetil{
  height: 60px;
  margin-left: 20px;
}
.dd-tab-btn{
  width: 130px;
}
/deep/.el-dialog.dialogClass{
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);

}
.el-form-item{
  margin-bottom: 5px !important;
}
</style>
